package com.yxb.cms.service;


import com.yxb.cms.architect.constant.BusinessConstants;
import com.yxb.cms.architect.constant.BussinessCode;
import com.yxb.cms.architect.utils.AppKeyUtils;
import com.yxb.cms.architect.utils.BussinessMsgUtil;
import com.yxb.cms.architect.utils.DbIdUtil;
import com.yxb.cms.dao.DbAuthManagerMapper;
import com.yxb.cms.domain.dto.BussinessMsg;
import com.yxb.cms.domain.vo.DbAuthManager;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 授权管理服务
 * @author YXB
 */
@Service
@Log4j2
public class AuthManagerService {


    @Autowired
    private DbAuthManagerMapper dbAuthManagerMapper;



    /**
     * 授权管理信息分页展示列表
     *
     * @return
     */
    public Map<String, Object> selectAuthManagerListByPage(DbAuthManager authManager) {
        Map<String, Object> map = new HashMap<>();
        try {
            List<DbAuthManager> authManagerList = dbAuthManagerMapper.selectAuthManagerListByPage(authManager);
            Long count = dbAuthManagerMapper.selectAuthManagerCount(authManager);

            map.put("code", 200);
            map.put("msg", "获取信息成功");
            map.put("count", count);
            map.put("data", authManagerList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "授权信息查询异常");
        }
        return map;
    }

    /**
     * 根据appkey查询授权信息<br>
     * 引用自GuavaCacheConfig，加入本地方缓存，cacheManager 使用默认的可以不指定 默认的为@Primary 注解的声明
     * @param authKey
     * @return
     */
    @Cacheable(value = "authManager", key = "#authKey")
    public DbAuthManager selectAuthManager(String authKey){
        return dbAuthManagerMapper.selectAuthManagerByAuthKey(authKey);
    }

    /**
     * 保存授权信息
     * @return
     */
    public BussinessMsg saveOrUpdateAuthManager(DbAuthManager authManager, String userId) {
        log.info("保存授权信息");
        long start = System.currentTimeMillis();
        try {

            //保存授权信息
            if(StringUtils.isEmpty(authManager.getAuthId())){

                authManager.setAuthId(DbIdUtil.generate());
                String authKey = AppKeyUtils.getAppKey();
                authManager.setAuthKey(authKey);
                authManager.setAuthSecret(AppKeyUtils.getAppSecret(authKey));

                authManager.setAuthStatus(BusinessConstants.STATUS_1.getCode());
                authManager.setCreaterUserId(userId);
                authManager.setCreaterTime(new Date());
                dbAuthManagerMapper.insertSelective(authManager);

            }else{

                authManager.setModifierTime(new Date());
                authManager.setModifierUserId(userId);
                dbAuthManagerMapper.updateByPrimaryKeySelective(authManager);
            }
        } catch (Exception e) {
            log.error("保存授权信息内部错误{}", e.getMessage(), e);
            throw e;
        } finally {
            log.info("保存授权信息结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);

    }


    /**
     * 删除授权信息
     */
    @Transactional
    public BussinessMsg delAuthManager(String appId,String currentUserId){
        log.info("删除授权信息信息开始,授权id{}",appId);
        long start = System.currentTimeMillis();
        try {
            DbAuthManager authManager = dbAuthManagerMapper.selectByPrimaryKey(appId);
            if(null != authManager){
                authManager.setAuthStatus(BusinessConstants.STATUS_0.getCode());
                authManager.setModifierUserId(currentUserId);
                authManager.setModifierTime(new Date());
                dbAuthManagerMapper.updateByPrimaryKey(authManager);
            }
        } catch (Exception e) {
            log.error("删除授权信息信息方法内部错误{}",e.getMessage(),e);
            throw e;
        }finally {
            log.info("删除授权信息结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }



}
